'use client';

import { useEffect, useRef } from 'react';
import { Terminal as XTerm } from 'xterm';
import { FitAddon } from 'xterm-addon-fit';
import { WebLinksAddon } from 'xterm-addon-web-links';
import { io } from 'socket.io-client';
import 'xterm/css/xterm.css';

export default function Terminal() {
  const terminalRef = useRef<HTMLDivElement>(null);
  const xtermRef = useRef<XTerm | null>(null);

  useEffect(() => {
    if (!terminalRef.current) return;

    // 初始化 xterm.js
    const xterm = new XTerm({
      cursorBlink: true,
      theme: {
        background: '#1e1e1e',
        foreground: '#ffffff',
      },
    });
    xtermRef.current = xterm;

    // 添加插件
    const fitAddon = new FitAddon();
    xterm.loadAddon(fitAddon);
    xterm.loadAddon(new WebLinksAddon());

    // 將終端機附加到 DOM
    xterm.open(terminalRef.current);
    fitAddon.fit();

    // 連接 WebSocket
    const socket = io('http://localhost:4000');

    // 處理終端機輸入
    xterm.onData((data) => {
      socket.emit('input', data);
    });

    // 處理終端機輸出
    socket.on('output', (data) => {
      xterm.write(data);
    });

    // 處理窗口大小變化
    const handleResize = () => {
      fitAddon.fit();
      const dimensions = {
        cols: xterm.cols,
        rows: xterm.rows,
      };
      socket.emit('resize', dimensions);
    };

    window.addEventListener('resize', handleResize);
    handleResize();

    // 清理函數
    return () => {
      window.removeEventListener('resize', handleResize);
      socket.disconnect();
      xterm.dispose();
    };
  }, []);

  return (
    <div className="h-full w-full bg-black">
      <div ref={terminalRef} className="h-full w-full" />
    </div>
  );
} 